<!--
 * @作者: kerwin
 * @公众号: 大前端私房菜
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script src="/javascripts/socketio.js"></script>
</head>

<body>
    <h1>聊天室</h1>
    <h1>当前用户:
        <b id="user"></b>
    </h1>
    <input type="text" id="text"><button id="send">send</button>

    <select id="select">

    </select>
    <!-- 建立socket连接 带着token，后端验证 -->
    <script>
        var select = document.querySelector("#select")
        var send = document.querySelector("#send")
        var text = document.querySelector("#text")
        var user = document.querySelector("#user")
        user.innerHTML = localStorage.getItem("username")
        const WebSocketType = {
            Error: 0, //错误
            GroupList: 1,
            GroupChat: 2,
            SingleChat: 3
        }
        //引入socket.io js端
        const socket = io(`ws://localhost:3000?token=${localStorage.getItem("token")}`); //默认 连接了localhost

        socket.on(WebSocketType.GroupChat, (msg) => {
            var title = msg.user ? msg.user.username : "广播"
            console.log(title + " : " + msg.data)
        })   
        socket.on(WebSocketType.SingleChat, (msg) => {
            var title = msg.user ? msg.user.username : "广播"
            console.log(title + " : " + msg.data)
        })   

        socket.on(WebSocketType.Error, (msg) => {
            localStorage.removeItem("token")
            location.href = "/login"
        })

        socket.on(WebSocketType.GroupList, (msgObj) => {
            // console.log(msg)
            const onlineList = msgObj.data
            select.innerHTML = ""
            select.innerHTML = `<option value="all">all</option>` + onlineList.map(item => `
                        <option value="${item.username}">${item.username}</option>
                    `).join("")
        })

        send.onclick = () => {
            if (select.value === "all") {
                // console.log("群发")
                socket.emit(WebSocketType.GroupChat,createMessage(text.value))
            } else {
                // console.log("siliao")
                socket.emit(WebSocketType.SingleChat,createMessage(text.value,select.value))
            }
        }

        function createMessage(data, to) {
            return {
                data,
                to
            }
        }
    </script>
</body>

</html>